package com.gorbas.springsocial.wicket;

import org.apache.wicket.Session;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.util.Assert;

public class OAuthEntryPoint extends WebPage {

	@SpringBean
	private OAuthEntryPointController authEntryPointController;

	public static final String PAGE_PARAMETER_MODE = "mode";
	public static final String PAGE_PARAMETER_PROVIDER = "provider";
	public static final String PAGE_PARAMETER_SCOPE = "scope";

	public static enum Mode {
		Login, Logout, Authenticate
	};

	private OAuthSessionIF getAuthSession() {
		Session session = getSession();
		Assert.isInstanceOf(OAuthSessionIF.class, session, String.format("Session should implements %s", OAuthSessionIF.class));
		return (OAuthSessionIF) session;
	}

	// Begin of general use methods
	private String getStringParam(String pageParamCode) {
		org.apache.wicket.util.string.StringValue paramValue = getPageParameters().get(pageParamCode);
		Assert.notNull(paramValue, String.format("%s should not be null", pageParamCode));
		Assert.isTrue(!paramValue.isNull(), String.format("%s should not be null", pageParamCode));
		return paramValue.toString();
	}

	private <E extends Enum> E getEnumParam(String pageParamCode, Class<E> enumType) {
		String value = getStringParam(pageParamCode);
		return (E) Enum.valueOf(enumType, value);
	}

	public OAuthEntryPoint(PageParameters pageParameters) {
		super(pageParameters);
		Mode mode = getEnumParam(PAGE_PARAMETER_MODE, Mode.class);
		String providerId = getStringParam(PAGE_PARAMETER_PROVIDER);

		switch (mode) {
		case Login: {
			String scope = getStringParam(PAGE_PARAMETER_SCOPE);
			authEntryPointController.login(providerId, scope);
		}
			break;
		case Authenticate: {
			authEntryPointController.authenticate(providerId);
		}
			break;
		case Logout: {
			authEntryPointController.logout();
		}
			break;
		default: {
			throw new RuntimeException(String.format("Unsupported mode %s", mode.toString()));
		}
		}
		if (getAuthSession().getUserId() != null) {
			if (!getPage().continueToOriginalDestination()) {
				setResponsePage(getApplication().getHomePage());
			}
		} else {
			error(getLocalizer().getString("exception.login", this));
		}
	}

}
